package org.jfsm.core;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class FSMOutput extends SignalGroup {

    public final class Signal extends FSMSignal {

        public void dispatch(FSMReplyContext replyCtx) {
            dispatcher.get(replyCtx.refid).dispatch(replyCtx.ctx, eid, null);
        }

        @Override
        int getEid() {
            // FIXME hack to save memory: use numSignals as offset during fsm.build()
            return numSignals + super.getEid();
        }
    }

    public final class SignalM<M> extends FSMSignalM<M> {

        SignalM(Field f) {
            super(f);
        }

        public void dispatch(FSMReplyContext replyCtx, M msg) {
            dispatcher.get(replyCtx.refid).dispatch(replyCtx.ctx, eid, msg);
        }

        @Override
        int getEid() {
            // hack to save memory: use numSignals as offset during fsm.build()
            return numSignals + super.getEid();
        }
    }

    private final ArrayList<Dispatcher> dispatcher = new ArrayList<Dispatcher>();

    @Override
    FSMSignal newSignalS(Field f) {
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    FSMSignal newSignalM(Field f) {
        return new SignalM(f);
    }

    @Override
    FSMSignal newSignal(Field f) {
        return new Signal();
    }

    int registerReference(int eidOffset) {
        dispatcher.add(new Dispatcher(eidOffset));
        return dispatcher.size() - 1;
    }

    void setWorker(int refID, FSMWorker worker) {
        dispatcher.get(refID).worker = worker;
    }

}
